package com.etlmaster.executor.steps.sql;

import javax.sql.DataSource;

import com.etlmaster.core.DataSourceDefine;
import com.etlmaster.core.DataSourceHolder;
import com.etlmaster.executor.Step;
import com.etlmaster.executor.StepMeta;
import com.etlmaster.executor.annotation.StepInstruction;
import com.etlmaster.executor.utils.MultiTenantDataSourceUtils;
import com.etlmaster.executor.utils.StepState;
/**
 * 
 * @author MeiKefu
 * @date 2014-8-15
 */
@StepInstruction("sql")
public class SqlStep extends Step{

	private SqlStepMeta meta;
	public SqlStep(StepMeta meta) {
		super(meta);
		this.meta=(SqlStepMeta)meta;
	}
	
	protected DataSource getDataSource(){
		return MultiTenantDataSourceUtils.getDataSource(meta.getDsName(), meta.getUserName(), meta.getPassword());
	}

	@Override
	protected int handle() {

		meta.getStepState().getReturnValue().put("logInfo", meta.getDsName()+":"+meta.getSql().replaceAll("'", "''"));

		DataSourceDefine def = DataSourceHolder.getInstance()
				.getDataSourceDefine(meta.getDsName());
	    if (def==null) {
	    	meta.log("ERROR","未分配数据库资源！" );
	      return StepState.RUNNING_FAILED;
	    }else{
			return SqlProcessor.getSqlProcessor(meta,this).process()?StepState.RUNNING_SUCCESSED:StepState.RUNNING_FAILED;
		}
	}
	
	@Override
	public boolean stop() {
		return false;
	}
	
}
